package com.hjm.app.activity;

import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.hjm.app.R;
import com.hjm.app.fragment.order.FragmentOrderAddress;
import com.hjm.app.fragment.order.FragmentOrderBase;
import com.hjm.app.fragment.order.FragmentOrderCreate;
import com.hjm.app.fragment.order.FragmentOrderDetail;
import com.hjm.app.fragment.order.OrderCallBackInterface;
import com.hjm.java.entity.Address;
import com.hjm.ui.common.HorizontalTextList;
import com.hjm.ui.common.TopBar;
import com.hjm.ui.order.adapter.OrderItemAdapter;
import com.hjm.ui.order.entity.Order;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单活动类
 */
public class OrderActivity extends BaseActivity implements OrderItemAdapter.OnItemClickListener, OrderCallBackInterface {
    public final static String TYPE = "type";
    public final static String TYPE_ADDRESS = "address";
    public final static String TYPE_ORDER_CREATE = "order_create";
    public final static String TYPE_ORDER_DETAIL = "order_detail";
    public final static String TYPE_ORDER_NO_PAY = "2";
    public final static String TYPE_ORDER_NO_TX = "3";
    public final static String TYPE_ORDER_NO_RX = "4";
    public final static String TYPE_ORDER_DONE = "5";
    public static final String ORDER_IDS = "order_ids";
    public static final String ORDER_COMMENT = "order_comment";

    private String type;
    private int[] orderIds;

    private FragmentOrderCreate fragmentOrderCreate;
    private TopBar topBar;
    private String TAG = "OrderActivity";
    private HorizontalTextList hTextList;

    private List<Order> orders;
    // 要显示详情的目标订单，当点击订单项时就会切换
    private Order detailTargetOrder;
    // 用户默认地址
    private Address defAddress;
    private Address txAddress;

    @Override
    void initView() {
        type = getIntent().getStringExtra(TYPE);
        orderIds = getIntent().getIntArrayExtra(ORDER_IDS);
        topBar = findViewById(R.id.top_bar);
        topBar.setOnBackClickListener((v) -> {
            finish();
        });
        // 制作导航栏数据
        List<Map<String, String>> mData = new ArrayList<Map<String, String>>() {{
            add(new HashMap<String, String>() {{
                put("text", "待支付");
                put("tag", TYPE_ORDER_NO_PAY);
            }});
            add(new HashMap<String, String>() {{
                put("text", "待发货");
                put("tag", TYPE_ORDER_NO_TX);
            }});
            add(new HashMap<String, String>() {{
                put("text", "待收货");
                put("tag", TYPE_ORDER_NO_RX);
            }});
            add(new HashMap<String, String>() {{
                put("text", "已完成");
                put("tag", TYPE_ORDER_DONE);
            }});
        }};
        hTextList = findViewById(R.id.horizontal_text_list);
        hTextList.setmData(mData);
        hTextList.setOnItemClickListener((type, p) -> {
            Log.d(TAG, "initView:点击了 " + type);
            switchOrderFragment(type);
        });

        Log.d(TAG, "initView: 初始化完成");
    }

    @Override
    void initData() {
        fragmentOrderCreate = FragmentOrderCreate.newInstance(new ArrayList<>());
        mFragmentMap.put(TYPE_ORDER_CREATE, fragmentOrderCreate);
        mFragmentMap.put(TYPE_ADDRESS, FragmentOrderAddress.newInstance());
//        updateFragment(type,null);
        initOrderList(type);
        Log.d(TAG, "initData: 数据初始化完成");
    }

    private void initOrderList(String type) {
        Log.d(TAG, "initOrderList: 初始化订单列表");
        // 获取默认收货地址
        getAddressDef();
        // 设置默认发货地址，只做展示
        txAddress = new Address();
        txAddress.setAddress("国美黑宫");
        txAddress.setName("登拜");
        txAddress.setPhone("911");

        if (type.equals(TYPE_ORDER_CREATE)) {
            updateFragment(type,null);
            creteOrder(orderIds);
        } else {
            updateOrderList(type);
        }
    }

    @Override
    int getView() {
        return R.layout.activity_order;
    }

    /**
     * 获取默认收货地址
     */
    void getAddressDef() {
        addressService.getAddressDef(
                address -> {
                    this.defAddress = address;
                    fragmentOrderCreate.setAddress(address);
                },
                msg -> {
                    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
                }
        );
    }

    /**
     * 创建订单
     * @param orderIds
     */
    void creteOrder(int[] orderIds) {
        orderService.createOrder(orderIds,
                () -> {
                    orders = orderService.getOrderList();
                    Log.d(TAG, "creteOrder: 创建订单返回的数据：" + orders);
                    Fragment fragment = mFragmentMap.get(TYPE_ORDER_CREATE);
                    if (fragment != null) {
                        ((FragmentOrderCreate) fragment).setOrderList(orders);
                        ((FragmentOrderCreate) fragment).setOrderCallBackInterface(this);
                    }
                },
                msg -> {
                    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
                });
    }

    /**
     * 初始化片段
     */
    void updateFragment(String type, Map<String, List<Order>> map) {
//        Log.d(TAG, "updateOrderList: 片段数据 "+(map!=null?map.get("2"):null));
//        Log.d(TAG, "updateOrderList: 片段数据 "+(map!=null?map.get("3"):null));
//        Log.d(TAG, "updateOrderList: 片段数据 "+(map!=null?map.get("4"):null));
//        Log.d(TAG, "updateOrderList: 片段数据 "+(map!=null?map.get("5"):null));
        mFragmentMap.put(TYPE_ORDER_NO_PAY, FragmentOrderBase.newInstance(map != null ? map.get("2") : new ArrayList<>()));
        mFragmentMap.put(TYPE_ORDER_NO_TX, FragmentOrderBase.newInstance(map != null ? map.get("3") : new ArrayList<>()));
        mFragmentMap.put(TYPE_ORDER_NO_RX, FragmentOrderBase.newInstance(map != null ? map.get("4") : new ArrayList<>()));
        mFragmentMap.put(TYPE_ORDER_DONE, FragmentOrderBase.newInstance(map != null ? map.get("5") : new ArrayList<>()));

        ((FragmentOrderBase) mFragmentMap.get(TYPE_ORDER_NO_PAY)).setOnItemClickListener(this);
        ((FragmentOrderBase) mFragmentMap.get(TYPE_ORDER_NO_TX)).setOnItemClickListener(this);
        ((FragmentOrderBase) mFragmentMap.get(TYPE_ORDER_NO_RX)).setOnItemClickListener(this);
        ((FragmentOrderBase) mFragmentMap.get(TYPE_ORDER_DONE)).setOnItemClickListener(this);
        if (type != null)
            switchOrderFragment(type);
    }

    void switchOrderFragment(String type) {
        switch (type) {
            case TYPE_ORDER_CREATE:
                Log.d(TAG, "onServiceConnection: 显示创建订单（获取订单创建的订单数据state，从state=1变为state=2）");
                topBar.setTitle("创建订单");
                hTextList.setVisibility(false);
                break;
            case TYPE_ADDRESS:
                Log.d(TAG, "onServiceConnection: 显示地址");
                topBar.setTitle("选择地址");
                hTextList.setVisibility(false);
                break;

            case TYPE_ORDER_DETAIL:
                Log.d(TAG, "onServiceConnection: 显示订单详情");
                topBar.setTitle("订单详情");
                hTextList.setVisibility(false);
                if (defAddress != null && txAddress != null){
                    ((FragmentOrderDetail) mFragmentMap.get(TYPE_ORDER_DETAIL)).setRxAddress(defAddress);
                    ((FragmentOrderDetail) mFragmentMap.get(TYPE_ORDER_DETAIL)).setTxAddress(txAddress);
                }
                break;

            case TYPE_ORDER_NO_PAY:
                Log.d(TAG, "onServiceConnection: 显示待支付");
                topBar.setTitle("待支付");
                hTextList.setItemSelect(type);
                hTextList.setVisibility(true);
                break;

            case TYPE_ORDER_NO_TX:
                Log.d(TAG, "onServiceConnection: 显示待发货");
                topBar.setTitle("待发货");
                hTextList.setItemSelect(type);
                hTextList.setVisibility(true);
                break;

            case TYPE_ORDER_NO_RX:
                Log.d(TAG, "onServiceConnection: 显示待收货");
                topBar.setTitle("待收货");
                hTextList.setItemSelect(type);
                hTextList.setVisibility(true);
                break;

            case TYPE_ORDER_DONE:
                Log.d(TAG, "onServiceConnection: 显示已完成");
                topBar.setTitle("已完成");
                hTextList.setItemSelect(type);
                hTextList.setVisibility(true);
                break;
        }
        switchFragmentPosition(type);
    }

    @Override
    public void onItemClick(Order order) {
        Log.d(TAG, "onItemClick: 点击了 " + order);
        // TODO:要去显示订单详情
        detailTargetOrder = order;
//        Log.d(TAG, "onItemClick: 测试能不能转化为子类 "+(com.hjm.back.entity.Order)order);  // 不用转化也有子类的属性
        int state = ((com.hjm.java.entity.Order) order).getState();
        mFragmentMap.put(TYPE_ORDER_DETAIL, FragmentOrderDetail.newInstance(String.valueOf(state), order));
        ((FragmentOrderDetail) mFragmentMap.get(TYPE_ORDER_DETAIL)).setOrderCallBackInterface(this);
        switchOrderFragment(TYPE_ORDER_DETAIL);
        // 设置顶部按钮返回点击事件不然一直直接结束订单活动
        topBar.setOnBackClickListener((v) -> {
            switchOrderFragment(state + "");
            // 当点击返回后，再恢复顶部按钮返回点击事件
            topBar.setOnBackClickListener((view) -> {
                finish();
            });
        });
    }

    @Override
    public void onButtonClickListener(String buttonText, List<Order> orderList) {
        Log.d(TAG, "onButtonClickListener: 按钮点击事件：" + buttonText + "，返回数据：" + orderList);
        switch (buttonText) {
            case "未支付-取消订单":
                orderService.deleteOrder(orderList.get(0).getOrderId(),
                        () -> {
                            Toast.makeText(this, "取消订单成功", Toast.LENGTH_SHORT).show();
                            finish();   // TODO:按照下面数据会重复出现
//                            updateOrderList(TYPE_ORDER_NO_PAY);
//                            // 从详情页返回后，恢复顶部按钮返回点击事件
//                            topBar.setOnBackClickListener((view) -> {
//                                finish();
//                            });
                        },
                        msg -> {
                            Toast.makeText(this, "取消订单失败 " + msg, Toast.LENGTH_SHORT).show();
                            switchOrderFragment(TYPE_ORDER_NO_PAY);
                            // 从详情页返回后，恢复顶部按钮返回点击事件
                            topBar.setOnBackClickListener((view) -> {
                                finish();
                            });
                        });
            case "取消支付":
                Log.d(TAG, "onButtonClickListener: 取消支付");
                updateOrderList(TYPE_ORDER_NO_PAY);
                break;

            case "支付":
                Log.d(TAG, "onButtonClickListener: 支付");
                orderService.updateOrderState(orderList.get(0).getOrderId(), OrderActivity.TYPE_ORDER_NO_TX,
                        () -> {
                            Toast.makeText(this, "支付成功", Toast.LENGTH_SHORT).show();
                            updateOrderList(TYPE_ORDER_NO_TX);
                            // 从详情页返回后，恢复顶部按钮返回点击事件
                            topBar.setOnBackClickListener((view) -> {
                                finish();
                            });
                        },
                        msg -> {
                            Toast.makeText(this, "支付失败 " + msg, Toast.LENGTH_SHORT).show();
                            switchOrderFragment(TYPE_ORDER_NO_PAY);
                            // 从详情页返回后，恢复顶部按钮返回点击事件
                            topBar.setOnBackClickListener((view) -> {
                                finish();
                            });
                        });
                break;

            case "待发货-取消订单":
                Log.d(TAG, "onButtonClickListener: 取消订单");
                orderService.deleteOrder(orderList.get(0).getOrderId(),
                        () -> {
                            Toast.makeText(this, "取消订单成功", Toast.LENGTH_SHORT).show();
                            updateOrderList(TYPE_ORDER_NO_TX);
                            // 从详情页返回后，恢复顶部按钮返回点击事件
                            topBar.setOnBackClickListener((view) -> {
                                finish();
                            });
                        },
                        msg -> {
                            Toast.makeText(this, "取消订单失败 " + msg, Toast.LENGTH_SHORT).show();
                            switchOrderFragment(TYPE_ORDER_NO_TX);
                            // 从详情页返回后，恢复顶部按钮返回点击事件
                            topBar.setOnBackClickListener((view) -> {
                                finish();
                            });
                        });
                break;

            case "确认收货":
                Log.d(TAG, "onButtonClickListener: 确认收货");
                orderService.updateOrderState(orderList.get(0).getOrderId(), OrderActivity.TYPE_ORDER_DONE,
                        () -> {
                            Toast.makeText(this, "确认收货成功", Toast.LENGTH_SHORT).show();
                            updateOrderList(TYPE_ORDER_DONE);
                            // 从详情页返回后，恢复顶部按钮返回点击事件
                            topBar.setOnBackClickListener((view) -> {
                                finish();
                            });
                        },
                        msg -> {
                            Toast.makeText(this, "确认收货失败 " + msg, Toast.LENGTH_SHORT).show();
                            switchOrderFragment(TYPE_ORDER_NO_RX);
                            // 从详情页返回后，恢复顶部按钮返回点击事件
                            topBar.setOnBackClickListener((view) -> {
                                finish();
                            });
                        });
                break;

            case "提醒发货":
                Log.d(TAG, "onButtonClickListener: 提醒发货");
                orderService.updateOrderState(orderList.get(0).getOrderId(), OrderActivity.TYPE_ORDER_NO_RX,
                        () -> {
                            Toast.makeText(this, "提醒成功", Toast.LENGTH_SHORT).show();
                            updateOrderList(TYPE_ORDER_NO_RX);
                            // 从详情页返回后，恢复顶部按钮返回点击事件
                            topBar.setOnBackClickListener((view) -> {
                                finish();
                            });
                        },
                        msg -> {
                            Toast.makeText(this, "提醒失败 " + msg, Toast.LENGTH_SHORT).show();
                            switchOrderFragment(TYPE_ORDER_NO_TX);
                            // 从详情页返回后，恢复顶部按钮返回点击事件
                            topBar.setOnBackClickListener((view) -> {
                                finish();
                            });
                        });
                break;

            case "店铺评价":
                Log.d(TAG, "onButtonClickListener: 店铺评价");
                Intent intent1 = new Intent(this, CommentActivity.class);
                intent1.putExtra("storeId", ((com.hjm.java.entity.Order) detailTargetOrder).getStoreId());
                intent1.putExtra("isNewComment", true);
                startActivity(intent1);
                finish();   // TODO:一个bug必须加
                break;

            case "商品评价":
                Log.d(TAG, "onButtonClickListener: 商品评价");
                Intent intent2 = new Intent(this, CommentActivity.class);
                intent2.putExtra("goodsId", detailTargetOrder.getGoodsId());
                intent2.putExtra("isNewComment", true);
                intent2.putExtra("orderId", detailTargetOrder.getOrderId());
                startActivity(intent2);
                finish();   // TODO:一个bug必须加
                break;
            case "点击商品":
                Log.d(TAG, "onButtonClickListener: 点击商品");
                Intent intent3 = new Intent(this, GoodsDetailActivity.class);
                intent3.putExtra("goodsId", orderList.get(0).getGoodsId());
                startActivity(intent3);
                finish();   // TODO:一个bug必须加
                break;
        }
    }

    void updateOrderList(String type) {
        Log.d(TAG, "updateOrderList: 更新订单列表");
        if (type != null)
            switchOrderFragment(type);
        orderService.getOrderList((isSuccess, map, msg) -> {
            updateFragment(type, map);
        });
    }
}